跳到主要内容

Spring 整合 Mybatis、Junit

Spring 集成 Junit

1、使用 @ExtendWith 注解替换原来的运行期 注意:原来的 Junit4 使用的是 @RunWith(SpringJUnit4ClassRunner.class)

2、使用 @ContextConfiguration 指定配置文件或配置类

3、使用 @Autowired 注入需要测试的对象

导入依赖,除了 Junit 外,Spring 也需要导入一个 Spring-test

<!-- 注意这里使用的是 Junit5 与 Junit4 是有区别的 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.5.RELEASE</version>
<scope>test</scope>
</dependency>



<!-- 原来的 Junit 包已经迁移到这里了 -->
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.6.2</version>
<scope>test</scope>
</dependency>

注:在 SpringBoot 里这个单元测试被集成了

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>

使用例

@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:applicationConfiguration.xml")
// 如果是使用注解配置的则:@ContextConfiguration(classes = {applicationConfiguration.class})
class UserServiceTest {

@Autowired
private UserService userService;

@Test
public void test(){
userService.sayHello();
}

}

坑:报错 Error creating bean with name 'mvcContentNegotiationManager':

单元测试时缺少环境

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>

MyBatis-spring

概述

MyBatis-spring官方文档

MyBatis-Spring 就是 MyBatis 写的一个在 Spring 环境下工作的依赖包,它可以让 MyBatis 直接使用到 Spring 的事务管理。

创建映射器 mapper 和 SqlSession 并注入到 bean 中,以及将 Mybatis 的异常转换为 Spring 的 DataAccessException。

配置DataSource

使用 Spring 的数据源替换 MyBatis 的配置c3p0dbcpdruid

原本是在 MyBatis 的 environments 里面配置的,而到了 Spring 之后可以直接把 DataSource Bean 交给 Spring 来管理,MyBatis 要用的话,Spring 会自动注入这个 DataSource 到 MyBatis 里面去

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="url" value="jdbc:mysql://localhost:3306/studyJDBC?useUnicode=true&amp; characterEncoding=utf8&amp;useSSL=true&amp;useServerPrepStmts=true"/>
<property name="password" value="123"/>
</bean>

读取 Properties 文件

除了像上面那样直接写死在 xml 文件里,还可以单独拿出一个 Properties 来写配置 DataSource 配置信息

<!-- 加载 properties 文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="username" value="${jdbc.username}"/>
<property name="url" value="${jdbc.url}"/>
<property name="password" value="${jdbc.password}"/>
</bean>

使用 XML 配置

配置 SqlSessionFactory

配置这个工厂 bean

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--绑定MyBatis的配置文件,这样就能结合使用mybatis-config.xml了-->
<property name="configuration" value="classpath:mybatis-config.xml"/>
<!--也可以在这里绑定Mapper-->
<property name="mapperLocations" value="classpath:com/alsritter/mapper/*.xml"/>
</bean>

配置 Mapper

假设定义了一个如下的 mapper 接口:

public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{userId}")
User getUser(@Param("userId") String userId);
}

那么可以通过 MapperFactoryBean 将接口加入到 Spring 中: 注意:MapperFactoryBean实现了 FactoryBean 这个接口,所以可以动态生成一个 Mapper 实例对象

这个 FactoryBean 接口是 Spring 专门提供用来实现工厂模式的

<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

使用例

public interface BookMapper {
// 查询全部书
@Select("select * from books")
List<Book> getAllBooks();
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="url"
value="jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=true&amp;useServerPrepStmts=true"/>
<property name="password" value="123"/>
</bean>

<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="dataSource" ref="dataSource"/>
</bean>

<bean class="org.mybatis.spring.mapper.MapperFactoryBean" id="bookMapper">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
<property name="mapperInterface" value="com.alsritter.dao.BookMapper"/>
</bean>

</beans>

在单元测试里使用上面创建的 Mapper

public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
BookMapper bookMapper = context.getBean("bookMapper", BookMapper.class);
List<Book> allBooks = bookMapper.getAllBooks();
allBooks.forEach(System.out::println);
}
}

使用注解来配置

配置 SqlSessionFactory

@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource());
return factoryBean.getObject();
}

配置Mapper

假设定义了一个如下的 mapper 接口:

public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{userId}")
User getUser(@Param("userId") String userId);
}

使用 Java 代码来配置的方式如下:

@Bean
public UserMapper userMapper() throws Exception {
SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory());
return sqlSessionTemplate.getMapper(UserMapper.class);
}

使用例

// 用 java 配置 Spring
@Configuration
public class MyConfig {

private static Logger logger = Logger.getLogger(MyConfig.class);

@Bean
public DriverManagerDataSource dataSource(){
DriverManagerDataSource dataSource = null;
try (InputStream fileReader = MyConfig.class.getClassLoader().getResourceAsStream("db.properties")) {
Properties properties = new Properties();
properties.load(fileReader);
dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(properties.getProperty("driver"));
dataSource.setUrl(properties.getProperty("url"));
dataSource.setUsername(properties.getProperty("username"));
dataSource.setPassword(properties.getProperty("password"));
}catch (IOException e){
logger.fatal("读取配置文件出错");
logger.fatal(e.getMessage());
}
return dataSource;
}

@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource());
// 绑定MyBatis的配置文件,结合MyBatis-config.xml使用
factoryBean.setConfigLocation(new InputStreamResource(Objects.requireNonNull(MyConfig.class.getClassLoader().getResourceAsStream("mybatis-config.xml"))));
return factoryBean.getObject();
}

@Bean
public SqlSessionTemplate sqlSession() throws Exception {
return new SqlSessionTemplate(sqlSessionFactory());
}

// 可以直接通过接口来创建出一个对象
@Bean
public UserMapper userMapper() throws Exception {
SqlSessionTemplate sqlSessionTemplate = sqlSession();
return sqlSessionTemplate.getMapper(UserMapper.class);
}
}

测试方法

@Test
public void test(){
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
UserMapper bean = context.getBean(UserMapper.class);
logger.info(bean.getUser(1));
}

★ SqlSessionTemplate

SqlSessionTemplate 是 MyBatis-Spring 的核心。

之前学习 SqlSession 是线程不安全的,每次执行完就需要被释放(如下)

try (SqlSession session = sqlSessionFactory.openSession()) {
BlogMapper mapper = session.getMapper(BlogMapper.class);
// 你的应用逻辑代码
}

SqlSessionTemplate 是线程安全的可以被多个 DAO 或映射器所共享使用

而其作为 SqlSession 的一个实现,所以可以无缝代替代码中已经在使用的 SqlSession(如下)

//注入以后就可以直接使用sqlsession
private SqlSessionTemplate sqlsession;
public void setSqlsession(SqlSessionTemplate sqlsession) {
this.sqlsession = sqlsession;
}

//用sqlsession去操作数据库
public void insert(Map user){
BlogMapper mapper = sqlsession.getMapper(BlogMapper.class);
mapper.insert("UserMapper.insert", user);
}

补充知识

FactoryBean

前面提到的创建一个 Bean 实例化直接注入就行了,然后就可以直接获取这个实例 但是还存在一种情况,就是传入一个接口想通过这个接口动态生成一个实现类(对,这里说的就是 MapperFactoryBean) 这时就可以使用 FactoryBean 这个接口了

这个接口的介绍:实现 BeanFactory 接口的对象其本身为单独的对象的工厂,需要使用工厂模式就可以使用这个接口

自动注入的问题

如果直接在

@Autowired
private BookMapper bookMapper;

上添加自动注入会报以下警告 @Autowired警告:Field injection is not recommended 解决办法是在Setter上使用自动注入

private BookMapper bookMapper;

// 把注入Dao注入进来
@Autowired
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}

无法读取

属性文件加载在统一的地方做,不要分模块加载即可。 一般就写在主配置文件里 例如 DataSource

<context:property-placeholder location="classpath:db.properties"/>